<template>
  <div class="map" id="layer"></div>
</template>

<script>
import Vue from "vue";
import wuhanGeoJson from "../config/wuhan.geoJson";
import landmark from "../config/landmark.json";
import infoPanel from "./infoPanel.vue";
import { loadModules } from "esri-loader";
import CustomLayer from "../domLayer";
export default {
  data() {
    return {};
  },
  mounted() {
    this.initMap();
  },
  methods: {
    async initMap() {
      const [Map, MapView, GeoJSONLayer, Polygon, Layer, Graphic] =
        await loadModules(
          [
            "esri/Map",
            "esri/views/MapView",
            "esri/layers/GeoJSONLayer",
            "esri/geometry/Polygon",
            "esri/layers/Layer",
            "esri/Graphic",
          ],
          {
            css: true,
          }
        );
      const wuhanBlob = new Blob([JSON.stringify(wuhanGeoJson)], {
        type: "application/json",
      });
      const WuHangGeoJSONLayer = new GeoJSONLayer({
        url: URL.createObjectURL(wuhanBlob),
        copyright: "Wuhan",
      });

      this.map = new Map({
        layers: [WuHangGeoJSONLayer],
      });
      this.mapView = new MapView({
        container: "layer",
        map: this.map,
        center: [114.296173, 30.592868],
        zoom: 4,
      });
      this.setMapConstraints(Polygon);
      this.initGraphics(Layer, Graphic);
    },
    async initGraphics(Layer, Graphic) {
      let graphics = [];
      for (const v of landmark) {
        const dom = new (Vue.extend(infoPanel))({
          propsData: {
            data: v,
          },
        }).$mount(document.createElement("div")).$el;
        const graphic = {
          geometry: {
            x: Number(v.longitude),
            y: Number(v.latitude),
            spatialReference: this.mapView.spatialReference,
          },
          dom,
          attributes: v,
        };
        graphics.push(graphic);
      }
      const MyCustomLayer = await CustomLayer.init();
      const layer = new MyCustomLayer({
        id: 5555,
        title: "自定义图层",
        graphics,
        visible: true,
        zoom: 4,
        placement: this.mapView.placement,
      });
      this.map.add(layer);
    },
    setMapConstraints(Polygon) {
      const chinaBoundary = new Polygon({
        rings: [
          [
            [113.996226, 30.419967],
            [113.996226, 30.739598],
            [114.665747, 30.739598],
            [114.665747, 30.419967],
            [113.996226, 30.419967],
          ],
        ],
        spatialReference: { wkid: 4326 },
      });

      this.mapView.constraints = {
        geometry: chinaBoundary,
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.map {
  width: 100%;
  height: 100%;
}
</style>
